from django import template
from django.db.models import Count
from django.db.models.functions import TruncMonth

from app01 import models

register = template.Library()


@register.inclusion_tag(filename='left_menu.html')
def tags(username):
    user_obj = models.UserInfo.objects.filter(username=username).first()
    blog = user_obj.blog
    category_list = models.Category.objects.filter(blog=blog).annotate(count_num=Count('article__pk')).values('name',
                                                                                                              'count_num',
                                                                                                              'pk')
    print(category_list)

    # 2. 查询当前用户所有的标签及标签下的文章数
    tag_list = models.Tag.objects.filter(blog=blog).annotate(count_num=Count('article__pk')).values('name', 'count_num',
                                                                                                    'pk')
    print(tag_list)

    # 3. 按照年月统计所有的文章
    date_list = models.Article.objects.filter(blog=blog).annotate(month=TruncMonth('create_time')).values(
        'month').annotate(count_num=Count('pk')).values('month', 'count_num')
    print(date_list)
    return locals()